package com.luxiu.extensionlib.adapter

import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import java.util.Collections

abstract class DraggableAdapter<T : ViewHolder?> : RecyclerView.Adapter<T>() {
    protected var mItemTouchHelper: ItemTouchHelper? = null
    private var mParentRecyclerView: RecyclerView? = null

    fun setRecyclerView(recyclerView: RecyclerView?, flag: Int): DraggableAdapter<T> {
        mParentRecyclerView = recyclerView
        mItemTouchHelper = ItemTouchHelper(DraggableTouchHelperCallBack(flag)).apply {
            attachToRecyclerView(recyclerView)
        }
        return this
    }

    var isLongPressDraggable = false

    inner class DraggableTouchHelperCallBack(private var flag: Int) : ItemTouchHelper.Callback() {

        override fun isLongPressDragEnabled(): Boolean = isLongPressDraggable

        override fun getMovementFlags(
            recyclerView: RecyclerView,
            viewHolder: ViewHolder,
        ): Int {
            if (flag == 0) {
                flag = ItemTouchHelper.UP or ItemTouchHelper.DOWN
            }
            return makeMovementFlags(flag, 0)
        }

        override fun onMove(
            recyclerView: RecyclerView,
            viewHolder: ViewHolder,
            target: ViewHolder,
        ): Boolean {
            val from = viewHolder.adapterPosition
            val to = target.adapterPosition
            val adapter = recyclerView.adapter as DraggableAdapter<*>
            if (isLongPressDraggable) {
                Collections.swap(adapter.getList(), from, to)
                adapter.notifyItemMoved(from, to)
                updateSortInData(from, to)
                return true
            }
            return false
        }

        override fun onSwiped(viewHolder: ViewHolder, direction: Int) {
        }
    }

    abstract fun getList(): ArrayList<*>

    abstract fun updateSortInData(from: Int, to: Int)
}